package com.alvinlkk.basic.chapter21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car {
    private boolean waxOn = false;   //是否打蜡了
    
    public synchronized void wax() {  //打蜡
        waxOn = true;
        notifyAll();   //通知其他挂起的人物
    }
    
    public synchronized void buffed() {  //抛光
        waxOn = false;
        notifyAll();
    }
    
    public synchronized void waitingForWaxing() throws InterruptedException {  //等待打蜡
        while(waxOn == false) {
            wait();
        }
    }
    
    public synchronized void waitingForBuffing() throws InterruptedException {
        while(waxOn == true) { 
            wait();
        }
    }
}

class WaxOn implements Runnable {
    
    private Car car;
    
    public WaxOn(Car car) {
        this.car = car;
    }
    
    @Override
    public void run() {
        while(!Thread.interrupted()) {
            System.out.println("WAX on ....");
            try {
                TimeUnit.SECONDS.sleep(1);
                car.wax();
                car.waitingForBuffing();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 class WaxOff implements Runnable {
     
     private Car car;
     
     public WaxOff(Car car) {
         this.car = car;
     }
     
    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                car.waitingForWaxing();
                System.out.println("Wax OFF!");
                TimeUnit.SECONDS.sleep(1);
                car.buffed();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
        }
    }
     
 }

public class WaxOMatic {
    public static void main(String[] args) throws InterruptedException {
        Car car = new Car();
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(new WaxOff(car));
        exec.execute(new WaxOn(car));
        TimeUnit.SECONDS.sleep(5);
        exec.shutdown();
    }
}
